package com.zzyl.nursing.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.vo.DeviceInfo;
import com.zzyl.nursing.vo.RoomVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Slf4j
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;


    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        clearCache();
        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        clearCache();
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    /**
     * 根据房间 id 获取房间视图对象
     *
     * @param id
     * @return
     */
    @Override
    public RoomVo getRoomById(Long id) {
        String key = CacheConstants.REDIS_KEY_ROOM_VO + ":" + id;
        //查询redis中是否存在数据
        String roomVo = redisTemplate.opsForValue().get(key);
        RoomVo roomVo1 = null;
        if (StringUtils.hasLength(roomVo)) {
            roomVo1 = JSON.parseObject(roomVo, RoomVo.class);
        }
        if (roomVo1 == null) {
            log.info("查询数据库RoomVo-id,{}", id);
            roomVo1 = roomMapper.getRoomById(id);
            //将数据存入redis中
            redisTemplate.opsForValue().set(key, JSON.toJSONString(roomVo1));
        }
        return roomVo1;
    }

    private Void clearCache() {
        redisTemplate.delete(CacheConstants.REDIS_KEY_ROOM_VO);
        return null;
    }

    /**
     * 获取房间及关联的床位和设备
     *
     * @param floorId
     * @return
     */
//    @Override
//    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
//        List<RoomVo> list = roomMapper.getRoomsWithDeviceByFloorId(floorId);
//        log.info("查询数据库{}", list);
//        //调用redisTemplate  获取数据
//        //遍历每一个房间
//        list.forEach(roomVo -> {
//            //获得房间的床位列表
//            roomVo.getBedVoList().forEach(bedVo -> {
//                bedVo.getDeviceVos().forEach(deviceInfo -> {
//                    System.out.println(deviceInfo);
//                    String deviceVos = String.valueOf(redisTemplate.opsForHash().get(CacheConstants.DEVICE_LAST_DATA_KEY, deviceInfo.getIotId())) ;
//                    List<DeviceData> list1 = JSONUtil.toList(deviceVos, DeviceData.class);
//                    // 将redis中的设备数据放入设备对象中
//                    deviceInfo.setDeviceDataVos(list1);
//                });
//            });
//        });
//        log.info("查询数据库{}", list);
//
//        //获取房间列表
//        list.forEach(roomVo -> {
//            roomVo.getDeviceVos().forEach(deviceInfo -> {
//                String deviceVos = String.valueOf(redisTemplate.opsForHash().get(CacheConstants.DEVICE_LAST_DATA_KEY, deviceInfo.getIotId())) ;
//                List<DeviceData> deviceDataList = JSONUtil.toList(deviceVos, DeviceData.class);
//                deviceInfo.setDeviceDataVos(deviceDataList);
//                });
//                // 将redis中的设备数据放入设备对象中
//            });
//
//        return list;
//    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 根据楼层id查询有智能设备的房间数据
     *
     * @param floorId 楼层id
     * @return 结果
     */
    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
        // SQL返回的数据是基础数据，找到的是房间、床位、设备（房间|床位）
        List<RoomVo> roomVos = roomMapper.getRoomsWithDeviceByFloorId(floorId);
        // 遍历roomVos，拿到每一个房间
        roomVos.forEach(roomVo -> {
            // 拿到每一个房间的设备列表deviceVos
            List<DeviceInfo> deviceVos = roomVo.getDeviceVos();
            // 遍历房间里设备的列表，拿到每一个设备，获取到这个设备在Redis中的数据
            deviceVos.forEach(deviceVo -> {
                String deviceDataListJSON = (String)redisTemplate.opsForHash().get(CacheConstants.DEVICE_LAST_DATA_KEY, deviceVo.getIotId());
                List<DeviceData> deviceDataList = JSONUtil.toList(deviceDataListJSON,DeviceData.class);
                // 将redis中的设备数据放入设备对象中
                deviceVo.setDeviceDataVos(deviceDataList);
            });

            // 获取到房间中的床位列表并遍历
            roomVo.getBedVoList().forEach(bedVo -> {
                // 获取到床位上的设备列表并遍历
                bedVo.getDeviceVos().forEach(deviceVo -> {
                    String deviceDataListJSON = (String)redisTemplate.opsForHash().get(CacheConstants.DEVICE_LAST_DATA_KEY, deviceVo.getIotId());
                    List<DeviceData> deviceDataList = JSONUtil.toList(deviceDataListJSON,DeviceData.class);
                    // 将redis中的设备数据放入设备对象中
                    deviceVo.setDeviceDataVos(deviceDataList);
                });
            });
        });

        return roomVos;
    }
}

